#!/bin/ash
pidof(){
	ps|grep "$@" |grep -v grep|awk '{print $1}'
}

getconfig() {
	grep "key$1" /etc/plugin_config |awk -F '=' '{print $2}'|awk '{print substr($1,2)}'|awk '{print substr($1,1,length($1)-2)}'
}

setconfig() {
	key="key$1";
	val=$2;
	newstr="$key = \"$val\";"
	config_path="/etc/plugin_config";
	if [[ -z "$(grep $key $config_path)" ]]; then
		echo $newstr >> $config_path
	else
		oldstr=$(grep $key $config_path)
		sed -i "s/$oldstr/$newstr/g" $config_path
	fi
}

urldecode(){
	awk 'BEGIN{for(i=0;i<10;i++)hex[i]=i;hex["A"]=hex["a"]=10;hex["B"]=hex["b"]=11;hex["C"]=hex["c"]=12;hex["D"]=hex["d"]=13;hex["E"]=hex["e"]=14;hex["F"]=hex["f"]=15;}{gsub(/\+/," ");i=$0;while(match(i,/%../)){;if(RSTART>1);printf"%s",substr(i,1,RSTART-1);printf"%c",hex[substr(i,RSTART+1,1)]*16+hex[substr(i,RSTART+2,1)];i=substr(i,RSTART+RLENGTH);}print i;}'
}

resetconfig(){
port=$1
cat << EOF > /filebrowser.json
{
  "port": $port,
  "root":"/userdata",
  "noAuth": false,
  "baseURL": "",
  "address": "0.0.0.0",
  "reCaptchaKey": "",
  "reCaptchaSecret": "",
  "database":"/filebrowser.db",
  "log": "stdout",
  "plugin": "",
  "scope":"/userdata",
  "allowCommands": true,
  "allowEdit": true,
  "allowNew": true,
  "commands": [
    "ash",
    "awk",
    "busybox",
    "cat",
    "chmod",
    "chown",
    "grep",
    "kill",
    "killall",
    "ls",
    "lua",
    "mkdir",
    "mount",
    "ping",
    "plugin_action",
    "plugin_download",
    "ps",
    "rm",
    "sed",
    "sh",
    "sleep",
    "taskmonitorDaemon",
    "top",
    "git",
    "svn",
    "ls",
    "cd"
  ]
}
EOF
}

model=$(cat /proc/xiaoqiang/model)
setconfig model $model
port=$(getconfig port)
if [[ -z "$port" ]]; then
	#statements
	port=8088
	setconfig port $port
	setconfig enable on
fi

enable="on"
while [[ "$enable" == "on" ]]; do
	#statements
	enable=$(getconfig enable)
	newport=$(getconfig port)
	if [[  "$port" != "$newport" ]]; then
		killall /filebrowser
		port="$newport"
		resetconfig $port
    #开子进程偶尔成功，大多数情况是失败因故去掉
		#/filebrowser -c filebrowser.json &
	fi
	sleep 3
done
